package com.daodaofun.weibo.service.impl;

import com.daodaofun.util.PageInfo;
import com.daodaofun.util.UserNamedUtil;
import com.daodaofun.weibo.dto.UserDto;
import com.daodaofun.weibo.mapper.UserMapper;
import com.daodaofun.weibo.model.User;
import com.daodaofun.weibo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void save(User user) {
        // 自动生成，采用工具类通用的东西
        user.setNickname(UserNamedUtil.randomName());
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }

    @Override
    public User findByUsername(String username) {

        return userMapper.findByUsername(username);
    }

    @Override
    public List<Long> findMasters(Long userId) {
        return userMapper.findMasters(userId);
//        return null;
    }

    @Override
    public List<UserDto> findByUsernameLike(String content) {
        return userMapper.findByUsernameLike(content);
    }

    @Override
    public void starOnOrOff(Integer of, Long followId, Long startId) {
        // 当前有没有这个人的关注的列表
//         stringRedisTemplate.keys("follows" + id);
        ZSetOperations<String, String> ops = stringRedisTemplate.opsForZSet();
        double score = System.currentTimeMillis();
        if(of == 1){
            // 关注的目标用户的粉丝集合要添加一个
            ops.add("fans"+startId,followId+"",score);
            ops.add("follows"+followId,startId+"",score);
        } else if (of == 0){
            ops.remove("follows"+followId,startId+"");
            ops.remove("fans"+startId,followId+"");
        }




    }

    @Override
    public Set<String> findFollows(Long userId) {
//        stringRedisTemplate.opsForZSet().count
        ZSetOperations<String, String> ops = stringRedisTemplate.opsForZSet();
        Set<String> members = ops.range("follows" + userId, 1, ops.size("follows" + userId));
//        = stringRedisTemplate.opsForZSet().("follows" + userId);
        //
        return members;
    }

    @Override
    public Set<String> findFans(Long userId,Integer pageNum) {
//        Set<String> members = stringRedisTemplate.opsForZSet().members("fans" + userId);
        ZSetOperations<String, String> ops = stringRedisTemplate.opsForZSet();


        Set<String> members = ops.reverseRange("fans" + userId, (pageNum - 1) * PageInfo.PAGE_SIZE_FANS, pageNum * PageInfo.PAGE_SIZE_FANS - 1);


//        Set<String> members = stringRedisTemplate.opsForZSet().range("fans" + userId, 1, 2_000_000_000);
//        return members;
        return members;
    }


    @Override
    public long countFollows(Long id) {
        Long size = stringRedisTemplate.opsForZSet().size("follows" + id);
        return size;
    }

    @Override
    public long countFans(Long id) {
       return stringRedisTemplate.opsForZSet().size("fans"+id);
    }

    @Override
    public List<UserDto> findFollowsUser(Long id) {
        // 1 先得到所有follow id
       Set<String> follows = findFollows(id);

       // 判断今天是否同步
       int isRedisSyncToMysql = isRedisSyncToMysql(id);
       if(isRedisSyncToMysql == 0){
           // 再同步一次
       }

       // 写的操作，降低查询速度
        List<UserDto> users = userMapper.findUsersByIds(follows);

        for(int i = 0 ; i < users.size() ; i++){
            users.get(i).setOn(true);
        }
        //        for ()
        // on的状态没有
        return users;
    }


    @Override
    public int isRedisSyncToMysql(Long id) {
        return userMapper.isRedisSyncToMysql(id);
//        return 0;
    }

    @Override
    public PageInfo<UserDto> findFansUser(Long id,Integer pageNum) {
        PageInfo<UserDto> page = new PageInfo<>();

        // 统计当前粉丝的总数量
        long total = findFansTotal(id);
        page.setTotal(total);
        // 1 先得到所有follow id
        Set<String> fans = findFans(id,pageNum);
        Map<String,Integer> map = new HashMap<>();
        Iterator<String> it = fans.iterator();

//

        // 写的操作，降低查询速度
        List<UserDto> users = userMapper.findUsersByIds(fans);

        List<UserDto> userDtos = new ArrayList<>();
//
//        while(true){
//
//        }

        while(it.hasNext()){
            String next = it.next();
            for(int i = 0 ;  i < users.size() ; i++){
                String tempId = users.get(i).getId() + "";
                System.out.println(tempId + "===" + next);
                if(tempId.equals(next)){
                    userDtos.add(users.get(i));
                    break;
                }

//                if((users.get(i).getId().toString()).equals(next)){
//                    userDtos.add(users.get(i));
//                    break;
//                }
            }
        }

        for(int i = 0 ; i < userDtos.size() ; i++){
            userDtos.get(i).setOn(true);
        }
        //        for ()
        // on的状态没有
        page.setList(userDtos);
        return page;
    }

    @Override
    public long findFansTotal(Long id) {
        return stringRedisTemplate.opsForZSet().size("fans"+id);
    }


}















